package com.example.myapplication;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

/**
 * @author: rongfeng
 * @date: 2020/12/29
 * @description
 */
public class ReadWords {

    public static void main(String[] args) {
        new ReadWords().start3();
    }

    public HashSet<String> words = new HashSet<>();

    public Set<String> start() {
        folderMethod2("D:\\word\\books");
        System.out.println(words.size());
        return words;
    }


    public Set<String> start3() {
        redFile(new File("D:\\word\\test\\daxue_B.txt"));
        System.out.println(words.size());
        return words;
    }

    public Set<String> start2() {
        folderMethod2("D:\\wrf\\books\\test\\txt");
        System.out.println(words.size());
        return words;
    }


    public void folderMethod2(String path) {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null != files) {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
//                        System.out.println("文件夹:" + file2.getAbsolutePath());
                        folderMethod2(file2.getAbsolutePath());
                    } else {
                        System.out.println("文件:" + file2.getAbsolutePath());
                        redFile(file2);
                    }
                }
            }
        } else {
//            System.out.println("文件不存在!");
        }
    }

    public void redFile(File file) {
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String text = null;
            while ((text = bufferedReader.readLine()) != null) {
                if (!text.equals("") && text != null) {
                    words.add(text.replaceAll("\\\\", ""));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void saveFile(Set<String> set, File file) {
        StringBuffer stringBuffer = new StringBuffer();
        for (String str : set) {
            stringBuffer.append(str + "\n");
        }
        try {
            if (file.exists()) {
                file.delete();
                file.createNewFile();
            }
            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            out.write(stringBuffer.toString());
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("保存完成 ");
    }


}
